//
//  FilterBrandView.swift
//  koolcar
//
//  Created by xiantian on 2023/11/27.
//

import UIKit
import TTIndexBar

typealias FilterBrandViewBlock = (KatashikiListData?, String)->Void

class FilterBrandView: UIView {
    var callBack: FilterBrandViewBlock?
    var dataArray: [KatashikiListData] = []
    var showFlag: Bool?
    var bkgView: UIButton = {
        let tempView = UIButton()
        tempView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.0)
        return tempView
    }()
    var contentView: UIView = {
        let tempView = UIView()
        tempView.backgroundColor = UIColor.white
        return tempView
    }()
    
    var carBrandView: FilterBrandListView! //品牌列表
    var carSeriesView: FilterBrandCarSeries! //车系列表
    var scrollView: UIScrollView!
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.clipsToBounds = true
        self.addSubview(bkgView)
        bkgView.addTarget(self, action: #selector(bkgViewAction), for: .touchUpInside)
        self.bkgView.addSubview(contentView)
        
        scrollView = UIScrollView()
        scrollView.isPagingEnabled = true
        scrollView.isScrollEnabled = false
        contentView.addSubview(scrollView)
        
        carBrandView = FilterBrandListView.init(frame: .zero)
        carBrandView.selectBrandBlock = {[weak self] brandItem in
            if brandItem == nil {
                //全部品牌
                self?.callBack?(nil, "")
                self?.handleClose()
            }else{
                self?.didSelectBrandAction(item: brandItem!)
            }
        }
        scrollView.addSubview(carBrandView)

        carSeriesView = FilterBrandCarSeries.init(frame: .zero)
        carSeriesView.selectCarSeriesBlock = {[weak self] (brand, series) in
            self?.callBack?(brand, series)
            self?.handleClose()
        }
        scrollView.addSubview(carSeriesView)
        
        self.addSnpLayout()
    }
    
    private func addSnpLayout(){
        self.bkgView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.bottom.equalTo(0)
        }
        
        self.contentView.snp.makeConstraints { make in
            make.top.equalTo(0)
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
        }
        
        scrollView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.width.equalTo(kScreenWidth)
            make.top.equalTo(0)
            make.height.greaterThanOrEqualTo(500)
            make.bottom.equalTo(0).priority(.high)
        }
        
        carBrandView.snp.makeConstraints { make in
            make.left.equalTo(0)
            make.top.equalTo(0)
            make.height.equalTo(0)
            make.width.equalTo(kScreenWidth)
        }

        carSeriesView.snp.makeConstraints { make in
            make.left.equalTo(kScreenWidth)
            make.top.equalTo(0)
            make.height.equalTo(0)
            make.width.equalTo(kScreenWidth)
        }
        
        self.layoutIfNeeded()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    @objc func bkgViewAction(){
        self.handleClose()
    }
    
    private func didSelectBrandAction(item: KatashikiListData){
        self.carSeriesView.selectBrand = item
        self.carSeriesView.tableView.reloadData()
        UIView.animate(withDuration: 0.24) {
            self.scrollView.contentOffset.x = kScreenWidth
        }
    }
    
    /**
     [
        "A": [KatashikiListData],
        "B": [KatashikiListData],
        "C": [KatashikiListData]
     ]
     */
    func startAnimation(){
        //dataArray 所有品牌列表
        let result = self.dataArray.reduce(into: [String: [KatashikiListData]]()) { dict, obj in
            let key = obj.first ?? "#"
            dict[key, default: []].append(obj)
        }
        //排列好的数据
        let sort = result.sorted { $0.key < $1.key }.map{[$0.key: $0.value]}
        self.carBrandView.dataArray = sort
        //self.carSeriesView.dataArray = sort

        //计算高度 450合适 A~Z的摆放
        var view_height: CGFloat = CGFloat(self.dataArray.count * 40)
        view_height = min(460, view_height)
        view_height = max(300, view_height)
        self.scrollView.contentSize = CGSize.init(width: kScreenWidth * 2, height: view_height)
        self.scrollView.snp.updateConstraints { make in
            make.height.greaterThanOrEqualTo(view_height)
        }
     
        self.contentView.snp.updateConstraints { make in
            make.top.equalTo(-view_height)
        }
        
        self.carBrandView.snp.updateConstraints { make in
            make.height.equalTo(view_height)
        }
        
        self.carSeriesView.snp.updateConstraints { make in
            make.height.equalTo(view_height)
        }
        
        self.updateConstraints()
        self.layoutIfNeeded()
        UIView.animate(withDuration: 0.4) {
            self.bkgView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0.6)
            self.contentView.snp.updateConstraints { make in
                make.top.equalTo(0)
            }
            self.layoutIfNeeded()
        } completion: { flag in
            self.showFlag = true
        }
    }
    
    func handleClose(){
        UIView.animate(withDuration: 0.4) {
            self.bkgView.backgroundColor = UIColor.init(hex: 0x000000, alpha: 0)
            self.contentView.snp.updateConstraints { make in
                make.top.equalTo(-self.contentView.frame.size.height)
            }
            self.layoutIfNeeded()
        } completion: { flag in
            if flag {
                self.showFlag = false
                self.removeFromSuperview()
            }
        }
    }
}
